articles

Home / DeveloperSection / Articles / Validation Styles in Bootstrap Working with MVC

Validation Styles in Bootstrap Working with MVC

Anonymous User16646 04-Mar-2015

Hi everyone in this article I’m explaining about Validation style in bootstrap.

Description:

Anyone who's done any work with ASP.NET MVC will know just how great the built in model validation and binding is. You create a model, you attach some attributes to describe its rules, and then you create a controller and a couple of actions to handle it, followed by a view or two. By using very minimum code, and a sprinkling of helpers in your Razor view, you have validation messages and input boxes that change colour and display appropriate error messages when something goes wrong, all without lifting a finger.

Unfortunately, the class names used to set the colours are not changeable, and are not a match for the visual styles used by bootstrap, which is a great shame because the bootstrap styles look really good, and really crisp. A quick trip to stack overflow will show you question after question where MVC users are asking for advice on how to make this all work in an easy and reliable manner, and there are all sorts of generally crazy solutions, most of which involve adding the bootstrap 'Less' source code files to your project and then modifying them to also be applied to the rule names used by ASP.NET MVC. Although this is a good long term solution, many times all you need is a quick bit of code for a one off use case to solve the problem, and writing a helper, or recompiling your own custom bootstrap build really is more of a hassle than it needs to be.

Unleash the Script:

"But you can't use JavaScript, What about graceful degradation?"

Well, yes, you have a point, but in all honesty, many sites these days manage quite happily to force people to use JS and don't have a problem with it. As for the argument for scripters and screen scrapers? Well, you're presenting a form for a hHuman to fill in, right? If someone's trying to scrape that... they're quite clearly doing it wrong. However, this post is not an argument for the merits of JS being enabled or not; this is just one approach you could decide to use if you want.

So how do we implement it?

Quite easily, as it happens.+

If you're using Bootstrap, you already have jQuery running because BS has a dependancy on it. All you need to do is look for the validation error classes to tell you which fields in the form currently have validation errors. Once you know which fields have errors, you just need to add/remove the appropriate BS classes to style things correctly.

Implementing the Code:

The first thing to do is to create an empty MVC application. You can create one with other views and such like already in if you want, but I'll be assuming the project is already empty. Note also that I'll be writing this article from the point of view of using MVC5 and the .NET 4.5 runtime.

The first thing we need is a simple controller, The following code will create you a home controller with two simple actions: one to serve up the initial test form, and one to accept the post and validate it.

HomeController.cs:
publicclassHomeController : Controller
    {
        //
        // GET: /Home/
 
        publicActionResult Index()
      {
         return View();
      }
 
      [HttpPost]
      publicActionResult Index(TestObject myObject)
      {
         if (!ModelState.IsValid)
         {
            ModelState.AddModelError("","There are form errors; pleasecorrect them to continue!");
            return View();
         }
 
         return View("NoErrors");
      }
 
    }

Next, we'll create a couple of razor views. The first one will use the various HTML helpers to draw our form, and the second will simply just be a page with a message on that we can redirect to if the form has no errors.

Index.cshtml:
@model BootstrapValidation.Models.TestObject
 
@{
    ViewBag.Title = "Index";
 
}
<br/>
<br/>
<divclass="">
    <divclass="col-md-6 col-md-offset-3 well">
        <divclass="page-header">
            <h2>Register</h2>
        </div>
        <p>
            Please fill in and submit the form below. Do try not
      filling bits in and causing errors to see the effect.
        </p>
 
        @Html.ValidationSummary(true)
 
        @using (Html.BeginForm("Index", "Home", FormMethod.Post,
      new { role = "form" }))
        {
            <divclass="form-group">
                @Html.LabelFor(m => m.FirstName, new { @class = "control-label" })
                <divclass="">
                    @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
                    <pclass="help-block">@Html.ValidationMessageFor(m => m.FirstName)</p>
                </div>
            </div>
 
            <divclass="form-group">
                @Html.LabelFor(m => m.Surname, new { @class = "control-label" })
                <divclass="">
                    @Html.TextBoxFor(m => m.Surname, new { @class = "form-control" })
                    <pclass="help-block"><spanstyle='color: background:yellow'>@Html.ValidationMessageFor(m => m.Surname)</span></p>
                </div>
            </div>
 
            <divclass="form-group">
                @Html.LabelFor(m => m.EmailAddress, new { @class = "control-label" })
                <divclass="">
                    @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control" })
                    <pclass="help-block">@Html.ValidationMessageFor(m => m.EmailAddress)</p>
                </div>
            </div>
 
            <divclass="form-group">
                <spanstyle='background: yellow'>@Html.LabelFor(m => m.UkPhoneNumber, new { @class = "control-label" })</span>
                <divclass="">
                    @Html.TextBoxFor(m => m.UkPhoneNumber, new { @class = "form-control" })
                    <pclass="help-block">@Html.ValidationMessageFor(m => m.UkPhoneNumber)</p>
                </div>
            </div>
 
            <divclass="form-group">
                <divclass="">
                    <buttonclass="btn btn-primary">
                        Submit
               <spanclass="glyphicon glyphicon-log-in"></span>
                    </button>
                </div>
            </div>
        }
    </div>
</div>

 

TestObject.cs:

Finally, we need a data model to test our form, so create the following class called 'TestObject.cs' in your models folder.

publicclassTestObject
    {
        [Required(ErrorMessage = "You must provide your first name")]
        [Display(Name = "First Name")]
        publicstring FirstName { get; set; }
 
        [Required(ErrorMessage = "You must provide your surname")]
        [Display(Name = "Last Name")]
        publicstring Surname { get; set; }
 
        [Required(ErrorMessage = "You must provide your email address")]
        [Display(Name = "E-Mail address")]
        [DataType(DataType.EmailAddress)]
        [EmailAddress]
        publicstring EmailAddress { get; set; }
 
        [Required(ErrorMessage = "You must provide your phone number")]
        [Display(Name = "UK Phone number")]
        [DataType(DataType.PhoneNumber)]
        [RegularExpression(@"((^\+{0,1}44\s{0,1})|^0|(\(0\)))\d{4}\s{0,1}\d{6}$")]
        publicstring UkPhoneNumber { get; set; }
    }

You'll also need to set up a razor layout page. Depending on how you do things, this may be already created for you automatically, in an empty MVC application. However, you'll likely need to add the following two files;

_ViewStart.cshtml:
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 

_Layout.cshtml:
<!DOCTYPEhtml>
 
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>@ViewBag.Title</title>
    <linkhref="~/Content/bootstrap.min.css"rel="stylesheet"/>
</head>
<body>
    <divclass="navbar navbar-inverse navbar-fixed-top">
        <divclass="container">
            <divclass="navbar-header">
                <buttontype="button" class="navbar-toggle"
                    data-toggle="collapse" data-target=".navbar-collapse">
                    <spanclass="icon-bar"></span>
                    <spanclass="icon-bar"></span>
                    <spanclass="icon-bar"></span>
                </button>
                @Html.ActionLink("MVC Application", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <divclass="navbar-collapse collapse">
                <ulclass="nav navbar-nav"></ul>
            </div>
        </div>
    </div>
 
    <divclass="container">
 
        <divclass="row">
            @RenderBody()
        </div>
 
        <footerclass="row">
            <p>&copy;@DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
 
    </div>
 
    <scriptsrc="~/Scripts/jquery-1.9.1.min.js"></script>
    <scriptsrc="~/Scripts/bootstrap.min.js"></script>
    <scriptsrc="~/Scripts/app.js"></script>
</body>
</html>

 

You can probably cut some code out of the layout file if you need to, but that's a good template to keep around for Bootstrap projects because it implements the minimum you need to get an app screen with menu bar up and running.

With all the files in place, you now need to add Bootstrap using NuGet.

Validation Styles in Bootstrap Working with MVC

Make sure you get the more up to date(3.3.2) version,.

With Bootstrap installed, compile and run your app, and you should hopefully see something like the following:

Validation Styles in Bootstrap Working with MVC

 

Add a new JavaScript file to your project and add the following code to it.

App.js:
$(function () {
    $('.validation-summary-errors').each(function () {
        $(this).addClass('alert');
        $(this).addClass('alert-danger');
    });
 
    $('form').each(function () {
        $(this).find('div.form-group').each(function () {
            if ($(this).find('span.field-validation-error').length > 0) {
                $(this).addClass('has-error');
                $(this).find('span.field-validation-error').
                   removeClass('field-validation-error');
            }
        });
    });
 
});

 

If you now build and run your project, and then try submitting an empty form again just as you did before, you should now see things are different.

Validation Styles in Bootstrap Working with MVC


I am a content writter !

Leave Comment

Comments

Liked By